// pages/programme/programme.js
const app = getApp()
var util = require("../../utils/utils.js");
var WxParse = require("../../wxParse/wxParse.js");

Page({
  showModalStatus: false,
  data: {
    currentData: 0,
    description: {},
    phonecall: '18027274621',
    selected: true,
    selected1: false,
    showHidden: true,
    showHidden1: false,
    isCollect: false, // 默认没有收藏
    collectId: null, //收藏id
    current: 0,
    isShowAllGroup: false,
    courseKeywords:[],
    timer: ''
  },
  phonecallevent: function(e) {
    wx.makePhoneCall({
      phoneNumber: "18027159229"
    })
  },
  /**获取跳转活动中心的id */
  getactiveId: function () {
    let that = this;
    let Id = that.data.productid;
    wx.request({
      url: app.httpUrl + '/course/queryCourseActivity',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: { productId: Id ,rows:1},
      method: "POST",
      success: (res) => {
        // console.log(res.data.data)
        this.setData({
          active: res.data.data.results[0]
        })
      }
    })
  },
  powerDrawer: function(e) {
    var currentStatu = e.currentTarget.dataset.statu;
    this.util(currentStatu)
  },
  util: function(currentStatu) {
    /* 动画部分 */
    // 第1步：创建动画实例 
    var animation = wx.createAnimation({
      duration: 200, //动画时长 
      timingFunction: "linear", //线性 
      delay: 0 //0则不延迟 
    });

    // 第2步：这个动画实例赋给当前的动画实例 
    this.animation = animation;

    // 第3步：执行第一组动画 
    animation.opacity(0).rotateX(-100).step();

    // 第4步：导出动画对象赋给数据对象储存 
    this.setData({
      animationData: animation.export()
    })

    // 第5步：设置定时器到指定时候后，执行第二组动画 
    setTimeout(function() {
      // 执行第二组动画 
      animation.opacity(1).rotateX(0).step();
      // 给数据对象储存的第一组动画，更替为执行完第二组动画的动画对象 
      this.setData({
        animationData: animation
      })

      //关闭 
      if (currentStatu == "close") {
        this.setData({
          showModalStatus: false
        });
      }
    }.bind(this), 200)

    // 显示 
    if (currentStatu == "open") {
      this.setData({
        showModalStatus: true
      });
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    wx.showToast({
      title: '加载中...',
      icon:"loading"
    })
    let productid = options.productid;
    this.setData({
      productid: productid
    });
    if (!app.isLogin()) {
      this.getUserInfo();
    } else {
      this.loadData();
    }
    this.getactiveId()
  },
  loadData: function() {
    this.loadProduct();
    this.initCollect();
    this.getcomment()
  },
  //获取当前滑块的index
  bindchange: function(e) {
    const that = this;
    that.setData({
      currentData: e.detail.current
    })
  },
  /**
   * 获取评论数据
   */
  getcomment:function(){
    let that = this;
    let Id = that.data.productid;
    wx.request({
      url: app.httpUrl + '/activity/live/queryChildGrowthExpect',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: { productId:Id},
      method: "POST",
      success: (res) => {
        // console.log(res.data.data.results.length==0)
        for(let a=0;a<res.data.data.results.length;a++){
          res.data.data.results[a].createTime = util.formatDate(res.data.data.results[a].createTime, 'M月D日 h:m');
        }
        that.setData({
          commentlist:res.data.data.results
        })
      }
    })
  },
  /**
   * 查看评论的图片
   */
  seephoto:function(e){
    let img = e.currentTarget.dataset.img;
    let index = e.currentTarget.dataset.index;
    let arr =[];
    let list = this.data.commentlist[index].attachList;
    for(let a =0; a<list.length;a++){
      let img = 'http://img.xue110.top/taoxuequ/'+list[a].attachUrl;
      arr.push(img)
    }
    wx.previewImage({
      urls: arr,
      current:img
    })
  },
  checkCurrent: function(e) {
    const that = this;
    if (that.data.currentData === e.target.dataset.current) {
      return false;
    } else {
      that.setData({
        currentData: e.target.dataset.current
      })
    }
  },
  loadProduct: function() {
    let that = this;
    let productId = this.data.productid;
    // 课程介绍接口
    wx.request({
      url: app.httpUrl + '/course/queryCourseDetail/' + productId,
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      method: "GET",
      success: (res) => {
        let description = res.data.data;
        // console.log(description)
        description.startDate = util.formatDate(description.startDate, 'Y年M月D日');
        description.endDate = util.formatDate(description.endDate, 'Y年M月D日');
        // console.log(description.courseKeyword)
        let courseKeyword = description.courseKeyword ? description.courseKeyword.split("、") : that.data.courseKeywords
        that.setData({
          description: description,
          courseKeywords: courseKeyword
        })
        this.currentView();
        if (description.signWay == 1) {
          this.queryRecommentGroupOrder(description.id);
        }
        wx.hideToast()
      }
    })
  },
  queryRecommentGroupOrder: function(productId) {
    wx.request({
      url: app.httpUrl + '/course/queryRecommentGroupOrder',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        productId: productId,
        rows: 8,
        page: 1
      },
      method: "POST",
      success: (res) => {
        if (res.data.code == '000') {
          this.setData({
            groupOrderList: res.data.data.results
          });
          if (res.data.data.results.length > 0) this.groupTime();
        }
      }
    })
  },
  initCollect: function() {
    let productId = this.data.productid;
    wx.request({
      url: app.httpUrl + '/collection/isCollection',
      header: {
        'xcx-xtoken': app.globalData.openid,
        'content-type': 'application/json' // 默认值
      },
      data: {
        sourceId: productId,
        sourceType: "course"
      },
      method: "POST",
      success: (res) => {
        if (res.data.code == '000') {
          this.setData({
            isCollect: res.data.data > 0 ? true : false,
            collectId: res.data.data
          });
        }
        wx.hideToast()
      }
    })
  },
  // 点击分享按钮
  share:function(){
    // console.log(111)
    this.onShareAppMessage();
  },
  longtouch: function(event) {
    var src = event.currentTarget.dataset.src; //获取data-src
    var index = event.currentTarget.dataset.index; //获取data-src
    var list = [];
    var imageList = this.data.sourceList[index].imageList;
    for (var i in imageList) {
      list.push(app.imgUrl + imageList[i].sysUrl);
    }
    wx.previewImage({
      current: src, // 当前显示图片的http链接 
      urls: list // 需要预览的图片http链接列表     
    })
  },
  // 点击收藏
  toggleCollect() {
    if (this.data.isCollect) {
      //已收藏，点击则取消
      wx.request({
        url: app.httpUrl + '/collection/delCollection',
        header: {
          'xcx-xtoken': app.globalData.openid,
          'content-type': 'application/json' // 默认值
        },
        data: {
          id: this.data.collectId,
        },
        method: "POST",
        success: (res) => {
          this.setData({
            isCollect: false,
            collectId: null
          });
          wx.showToast({
            title: '已取消收藏',
            icon: 'success'
          })
        }
      })
    } else {
      wx.request({
        url: app.httpUrl + '/collection/addCollection',
        header: {
          'xcx-xtoken': app.globalData.openid,
          'content-type': 'application/json' // 默认值
        },
        data: {
          sourceId: this.data.productid,
          sourceType: "course"
        },
        method: "POST",
        success: (res) => {
          this.setData({
            id: res.data.data,
            isCollect: true,
          });
          wx.showToast({
            title: '已收藏成功',
            icon: 'success'
          })
        }
      })
    }
  },
  currentView() {
    WxParse.wxParse('detailsHtml', 'html', util.base64.decode(this.data.description.courseDetails), this, 5);
    // WxParse.wxParse('transplanHtml', 'html', util.base64.decode(this.data.description.tripPlan), this, 5);
  },
  toggleView(e) {
    var current = e.currentTarget.dataset.current || 0;
    wx.showToast({
      title: '加载中...',
      icon:"loading",
    })
    this.setData({
      current
    });
    wx.hideToast()
  },
  onShareAppMessage: function(res) {

  },
  getUserInfo: function () {
    let that = this;
    if (app.globalData.appUser != null) {
      return;
    }
    wx.login({
      success: function (res) {
        if (res.code) {
          //发起网络请求
          wx.request({
            url: app.httpUrl + '/common/getUserInfo',
            data: {
              code: res.code
            },
            header: {
              'content-type': 'application/json' // 默认值
            },
            method: "POST",
            success: function (res) {
              if (res.data.code == '000') {
                app.globalData.appUser = res.data.data;
                app.globalData.openid = res.data.data.openid;
                that.setData({
                  appUser: app.globalData.appUser
                })
                that.loadData();
              }
            }
          })
        } else {
          // console.log('登录失败！' + res.errMsg)
        }
      }
    });
  },
  groupMoreTab: function () {
    this.setData({
      isShowAllGroup: this.data.isShowAllGroup ? false : true
    })
  },
  /**跳转活动中心 */
  jump_active:function(e){
    let activityId = e.currentTarget.dataset.id;
    app.globalData.activityId = activityId;
    wx.switchTab({
      url: '/pages/study/study'
    })
  },
  groupTime: function () {
    let that = this;
    var list = that.data.groupOrderList;
    that.setData({
      timer: setInterval(function () {
        for(var i in list) {
          list[i].downtime = that.getTimestr(list[i].invalidTime);
        }
        that.setData({ groupOrderList: list})
      }, 1000)
    })
  },
  getTimestr: function (end) {
    var now = new Date().getTime();
    var leftTime = end - now;
    //定义变量 d,h,m,s保存倒计时的时间
    var d, h, m, s;
    var downtime = {
      d: '0', h: '00', m: '00', s: '00'
    }
    if (leftTime >= 0) {
      downtime.d = Math.floor(leftTime / 1000 / 60 / 60 / 24);
      h = Math.floor(leftTime / 1000 / 60 / 60 % 24);
      downtime.h = h < 10 ? '0' + h : h;
      m = Math.floor(leftTime / 1000 / 60 % 60);
      downtime.m = m < 10 ? '0' + m : m;
      s = Math.floor(leftTime / 1000 % 60);
      downtime.s = s < 10 ? '0' + s : s;
    }
    return "剩" + downtime.d + "天" + downtime.h + ":" + downtime.m + ":" + downtime.s;
  }
})